'use strict';

const co = require("co");
const md5 = require("md5");
const phantom = require("phantom");
let request = require("request");
let fs = require("fs");

module.exports = function (router) {

    router.get('/', function (req, res) {
        res.send('<code><pre>' + JSON.stringify({a: 11, now: Date.now()}, null, 2) + '</pre></code>');
    });

    router.get("/render", function (req, res) {
        res.render("index.ejs", {title: "Hello world!"});
    });

    router.get("/grab", grabHtml);

    router.get("/spider", spider);

    router.get("/mama", mama);
};

function grabHtml(req, res) {
    co(function* () {
        let url = req.query.url ? req.query.url : "http://www.baidu.com";
        let delay = parseInt(req.query.delay) ? parseInt(req.query.delay) : 500;

        url = decodeURI(url);

        if (!url) {
            return res.send({success: false, message: "网站不可为空"});
        }

        let instance = yield phantom.create();
        let page = yield instance.createPage();

        yield page.property("viewportSize", {
            width: 1920,
            height: 1080
        });

        let status = yield page.open(url);

        if (status == "success") {
            setTimeout(function () {
                co(function* () {
                    let base64 = yield page.renderBase64("PNG");
                    base64 = "data:image/png;base64," + base64;
                    // res.send("<html><head></head><body><div style=\"background-image: url(" + base64 + ") \"></div></body></html>");
                    res.send("<html><head></head><body><img src=\"" + base64 + " \" /></body></html>");
                    instance.exit();
                });
            }, delay);
        }
    });
}

function ranStr(withTimestamp = true, prefix = false) {
    let length = 10;
    let arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

    let str = "";
    let arrLength = arr.length;

    for (let i = 0; i < length; i++) {
        let ran = parseInt(Math.random() * arrLength);
        str += arr[ran];
    }

    return md5(str);
}

function spider(req, res) {
    co(function* () {
        let url = "http://www.pinking.net.cn/";

        let instance = yield phantom.create();
        let page = yield instance.createPage();

        yield page.on("onResourceReceived", function (receiveid) {
            console.info('Requesting', requestData)
        });

        let status = yield page.open(url);

        if (status == "success") {
            let base64 = yield page.renderBase64("PNG");
            instance.exit();
        }
    });
}

function mama(req, res) {
    co(function* () {
        let url = req.query.url ? req.query.url : "http://www.baidu.com";
        let path = req.query.path ? req.query.path : "default";
        let delay = parseInt(req.query.delay) ? parseInt(req.query.delay) : 500;

        url = decodeURIComponent(url);

        if (!url) {
            return res.send({success: false, message: "网站不可为空"});
        }

        let instance = yield phantom.create();
        let page = yield instance.createPage();

        yield page.on("onResourceReceived", function (receiveid) {
            co(function* () {
                delete receiveid.headers;
                console.info('Requesting', receiveid);

                let name = receiveid.url.split("?")[0];
                name = name.split("/");
                name = name[name.length - 1];
                console.log(name);
                let contentType = receiveid.contentType;

                let dir = "D:\\tmp\\" + path + "\\";

                console.log(receiveid);

                if (receiveid.stage === "end") {
                    if (contentType == "text/html") {
                        download(receiveid.url, dir + "html", name);
                    } else if (contentType == "text/css") {
                        download(receiveid.url, dir + "css", name);
                    } else if (contentType.indexOf("javascript") > -1) {
                        download(receiveid.url, dir + "js", name);
                    } else if (contentType.indexOf("image") > -1) {
                        download(receiveid.url, dir + "imgs", name);
                    }
                }
            });
        });

        yield page.property("viewportSize", {
            width: 1920,
            height: 1080
        });

        let status = yield page.open(url);

        if (status == "success") {
            setTimeout(function () {
                co(function* () {
                    let base64 = yield page.renderBase64("PNG");
                    base64 = "data:image/png;base64," + base64;
                    // res.send("<html><head></head><body><div style=\"background-image: url(" + base64 + ") \"></div></body></html>");
                    res.send("<html><head></head><body><img src=\"" + base64 + " \" /></body></html>");
                    instance.exit();
                });
            }, delay);
        }
    });
}

function download(url, dir, filename) {
    request.head(url, function (err, res, body) {
        request(url).pipe(fs.createWriteStream(dir + "/" + filename));
    });
};